<template>
  <div class="map-browsing-container">
    <div class="map-container" ref="mapContainer"></div>

    <!-- Control Panel -->
    <div class="control-panel" id="tools-container">
      <h3 class="panel-title">地图浏览</h3>
      <p class="panel-description">点击地图上的设施或道路查看详细信息</p>

      <el-select
        v-model="selectedLayers"
        multiple
        collapse-tags
        placeholder="选择显示图层"
        :teleported="false"
        @change="toggleLayers"
        class="layer-select"
      >
        <el-option
          v-for="item in layerOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>

    <!-- Feature Attributes Dialog -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" :modal="false">
      <el-form label-width="120px" class="attribute-form">
        <template v-for="(value, key) in attributes" :key="key">
          <!-- 只显示S103详细信息字段 -->
          <el-form-item v-if="key === 'S103详细信息'" :label="getLabel(key)">
            <div class="introduction-text s103-details">{{ formatS103Details(value) }}</div>
          </el-form-item>
          <!-- 对于设施，显示基本信息 -->
          <template v-else-if="!isRoadFeature()">
            <!-- 设施名称 - 所有类型都显示 -->
            <el-form-item v-if="key === 'facilityname'" :label="getLabel(key)">
              {{ value || '无数据' }}
            </el-form-item>
            <!-- 设施类型 - 所有类型都显示 -->
            <el-form-item v-if="key === 'facilitytype'" :label="getLabel(key)">
              {{ value || '无数据' }}
            </el-form-item>
            <!-- 图片字段 - 驿站和景点显示 -->
            <el-form-item
              v-if="(key === 'FacilityImage' || key === 'RoadImage') && shouldShowField(attributes.facilitytype, 'image')"
              :label="getLabel(key)"
            >
              <div class="image-container">
                <img
                  v-if="value"
                  :src="value"
                  class="attribute-image"
                  @click="previewImage(value)"
                />
                <div v-else class="no-image">暂无图片</div>
              </div>
            </el-form-item>
            <!-- 介绍字段 - 景点显示 -->
            <el-form-item v-if="key === 'FacilityIntroduction' && shouldShowField(attributes.facilitytype, 'introduction')" :label="getLabel(key)">
              <div class="introduction-text">{{ value || '无介绍' }}</div>
            </el-form-item>
            <!-- 状态字段 - 所有类型都显示，但标签不同 -->
            <el-form-item
              v-if="key === 'Status' && attributes.facilitytype"
              :label="getStatusLabel(attributes.facilitytype, key as string)"
            >
              {{ value || '无数据' }}
            </el-form-item>
          </template>
        </template>

        <!-- 设施类型专用字段 - 移到循环外部，避免重复显示 -->
        <template v-if="!isRoadFeature()">
          <!-- 驿站专用字段 -->
          <template v-if="attributes.facilitytype === '驿站' && parsedOtherJson">
            <el-form-item v-if="parsedOtherJson.serviceTime" label="服务时间">
              {{ parsedOtherJson.serviceTime }}
            </el-form-item>
            <el-form-item v-if="parsedOtherJson.equipmentStatus" label="设备状态">
              {{ parsedOtherJson.equipmentStatus }}
            </el-form-item>
          </template>

          <!-- 景点专用字段 -->
          <template v-if="attributes.facilitytype === '景点' && parsedOtherJson">
            <el-form-item v-if="parsedOtherJson.parkingSpaces" label="车位余量">
              {{ parsedOtherJson.parkingSpaces }}
            </el-form-item>
            <el-form-item v-if="parsedOtherJson.chargingPiles" label="充电桩数量">
              {{ parsedOtherJson.chargingPiles }}
            </el-form-item>
          </template>

          <!-- 餐饮专用字段 -->
          <template v-if="attributes.facilitytype === '餐饮' && parsedOtherJson">
            <el-form-item v-if="parsedOtherJson.businessInfo" label="营业信息">
              <div class="introduction-text">{{ parsedOtherJson.businessInfo }}</div>
            </el-form-item>
            <el-form-item v-if="parsedOtherJson.contactInfo" label="联系方式">
              {{ parsedOtherJson.contactInfo }}
            </el-form-item>
            <el-form-item v-if="parsedOtherJson.rating" label="评分等级">
              {{ getRatingStars(parsedOtherJson.rating) }}
            </el-form-item>
          </template>
        </template>
      </el-form>
    </el-dialog>

    <!-- Multiple Features Selection Dialog -->
    <el-dialog v-model="selectDialogVisible" title="请选择要素" width="500px" :modal="false">
      <template #header>
        <div class="dialog-header">
          <span>请选择要素</span>
        </div>
      </template>
      <div class="feature-selector">
        <el-table :data="selectedFeatures" style="width: 100%" class="feature-table">
          <el-table-column prop="attributes.facilityname || attributes.RoadName" label="名称">
            <template #default="{ row }">
              {{ row.attributes.facilityname || row.attributes.RoadName || '未命名要素' }}
            </template>
          </el-table-column>
          <el-table-column prop="layer.id" label="要素类型">
            <template #default="{ row }">
              {{ getLayerType(row.layer.id) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ $index }">
              <el-button
                type="primary"
                size="small"
                @click="handleSelect($index)"
                class="select-btn"
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="imagePreviewVisible" width="80%" :modal="false" :show-close="true">
      <div class="image-preview-container">
        <img :src="previewImageUrl" class="preview-image" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import Graphic from '@arcgis/core/Graphic'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Query from '@arcgis/core/rest/support/Query.js'
import Handles from '@arcgis/core/core/Handles.js'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import {
  facilityPointSymbol,
  scenicPointSymbol,
  viewScenicSpotSymbol,
  serviceSymbol,
  monitorSymbol,
  trafficSymbol,
  greenSymbol
} from '@/utils/facilityIcons'

const mapContainer = ref<HTMLDivElement>()

// 使用统一的设施图标符号（已从 facilityIcons.ts 导入）

// Create road symbol
const roadSymbol = new SimpleLineSymbol({
  color: [0, 122, 194, 0.8],
  width: 4,
  style: 'solid',
  cap: 'round',
  join: 'round',
})

// Create facility layer
const facilityLayer = new FeatureLayer({
  url: 'https://services.arcgis.com/cxicHGWOCJwYXasp/arcgis/rest/services/Facility/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'unique-value',
    field: 'facilitytype',
    defaultSymbol: facilityPointSymbol,
    uniqueValueInfos: [
      {
        value: '驿站',
        symbol: scenicPointSymbol,
      },
      {
        value: '景点',
        symbol: viewScenicSpotSymbol,
      },
      {
        value: '餐饮',
        symbol: facilityPointSymbol,
      },
    ],
  } as never,
})

// Create road layer
const roadLayer = new FeatureLayer({
  url: 'https://www.geosceneonline.cn/server/rest/services/Hosted/S103/FeatureServer/0',
  outFields: ['*'],
  renderer: {
    type: 'simple',
    symbol: roadSymbol,
  } as never,
})

// Create sketch layer for drawing
const sketchLayer = new GraphicsLayer({
  title: '绘图图层',
})

// Create map
const map = new Map({
  basemap: {
    baseLayers: [gaodeLayer],
  },
})

// Add layers to map
map.add(facilityLayer)
map.add(roadLayer)
map.add(sketchLayer)

// Create map view
const view = new MapView({
  map: map,
  center: [117.14435714426122, 36.29746937366678],
  zoom: 10,
})

// Layer options for toggling
const layerOptions = [{ label: '道路设施', value: facilityLayer.id }]
const allLayers = [facilityLayer]

// Toggle layers visibility
function toggleLayers(value: string[]) {
  allLayers.forEach((layer) => {
    layer.visible = value.includes(layer.id)
  })
}

// State variables
const selectedLayers = ref([facilityLayer.id])
const dialogVisible = ref(false)
const attributes = ref<{ [key: string]: any }>({})
const dialogTitle = ref('要素属性')
const selectDialogVisible = ref(false)
const selectedFeatures = ref<any[]>([])
const selectedFeatureIndex = ref(0)
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')
const parsedOtherJson = ref<{ [key: string]: any } | null>(null)
const highlightHandle: Handles = new Handles() // 高亮显示句柄
let selectFeatureLayer: FeatureLayer | null = null
let selectGraphic: Graphic | null = null
let allSelectGraphics: Graphic[] = []

onMounted(() => {
  // Initialize map view container
  view.container = mapContainer.value as HTMLDivElement
  view.ui.add('tools-container', 'top-right')

  // Set up click event handler
  view.on('click', async (event) => {
    // Query facility layer
    const facilityQuery = new Query({
      geometry: event.mapPoint,
      distance: 500, // Query radius
      units: 'meters',
      spatialRelationship: 'intersects',
      outFields: ['*'],
      returnGeometry: true,
    })

    // Query road layer
    const roadQuery = new Query({
      geometry: event.mapPoint,
      distance: 500, // Road query radius
      units: 'meters',
      spatialRelationship: 'intersects',
      outFields: ['*'],
      returnGeometry: true,
    })

    try {
      // Query both layers in parallel
      const [facilityResponse, roadResponse] = await Promise.all([
        facilityLayer.queryFeatures(facilityQuery),
        roadLayer.queryFeatures(roadQuery),
      ])

      // Combine query results
      const features = [...facilityResponse.features, ...roadResponse.features]

      if (features.length === 0) {
        ElMessage.info('该位置没有可显示的要素属性')
      } else if (features.length === 1) {
        // Show single feature directly
        const feature = features[0]
        selectFeatureLayer = feature.layer as FeatureLayer
        selectGraphic = feature
        showAttributes(feature)
      } else {
        // Show selection dialog for multiple features
        selectedFeatures.value = features.map((g) => ({
          attributes: structuredClone(g.attributes),
          geometry: structuredClone(g.geometry),
          layer: { id: g.layer?.id },
        }))
        allSelectGraphics = features
        selectedFeatureIndex.value = 0
        selectDialogVisible.value = true
      }
    } catch (error) {
      console.error('查询要素失败:', error)
      ElMessage.error('查询要素失败')
    }
  })
})

// Get layer type based on layer ID
function getLayerType(id: string) {
  if (id === facilityLayer.id) {
    return '设施'
  } else if (id === roadLayer.id) {
    return '道路'
  }
  return '未知类型'
}

// Get feature layer by ID
function getSelectFeatureLayer(id: string) {
  if (id === facilityLayer.id) {
    return facilityLayer
  } else if (id === roadLayer.id) {
    return roadLayer
  }
  return facilityLayer // Default to facility layer
}

// Handle feature selection
function handleSelect(index: number) {
  selectedFeatureIndex.value = index
  confirmSelection()
}

// Confirm feature selection
function confirmSelection() {
  selectFeatureLayer = getSelectFeatureLayer(
    selectedFeatures.value[selectedFeatureIndex.value].layer.id,
  )!
  selectGraphic = allSelectGraphics[selectedFeatureIndex.value]
  showAttributes(selectedFeatures.value[selectedFeatureIndex.value] as __esri.Graphic)
  selectDialogVisible.value = false
}

// Show feature attributes
function showAttributes(feature: __esri.Graphic) {
  // Clear previous highlight
  highlightHandle.removeAll()

  // Highlight selected feature
  if (selectFeatureLayer && selectGraphic) {
    // Create a highlight graphic
    const highlightSymbol =
      selectFeatureLayer.id === facilityLayer.id
        ? {
            type: 'simple-marker',
            style: 'circle',
            color: [255, 255, 0, 0.8],
            size: '16px',
            outline: {
              color: [255, 255, 0, 0.8],
              width: 3,
            },
          }
        : {
            type: 'simple-line',
            color: [255, 255, 0, 0.8],
            width: 6,
          }

    const highlightGraphic = new Graphic({
      geometry: selectGraphic.geometry,
      symbol: highlightSymbol as any,
    })

    // Add highlight graphic to view
    view.graphics.add(highlightGraphic)

    // Store the highlight handle for later removal
    highlightHandle.add({
      remove: () => {
        view.graphics.remove(highlightGraphic)
      },
    })
  }

  // Set dialog title based on feature type
  if (feature.layer?.id === facilityLayer.id) {
    dialogTitle.value = `设施: ${feature.attributes.facilityname || '未命名设施'}`
  } else if (feature.layer?.id === roadLayer.id) {
    const roadName = feature.attributes.RoadName || '济南S103'
    dialogTitle.value = `道路: ${roadName}`

    // 默认显示济南S103道路详细信息
    const s103Details = {
      起点: '红符路口南侧',
      终点: '济南泰安界',
      总长度: '29.435公里',
      改建段长度: '21.850公里（起点至槲疃）',
      原路改建段: '7.585公里（槲疃至泰安界）',
      技术标准: '双向六/四车道一级公路',
      设计速度: '80公里/小时',
      主要设施: '大桥4座、互通立交1处、分离立交2处、旅游服务设施8处',
      项目性质: '生态旅游公路项目',
      建设意义: '提升103省道行车条件，缓解沿线景区拥堵，促进济南泰安联系，带动沿线旅游资源开发',
    }

    // 将详细信息添加到属性中
    feature.attributes = {
      ...feature.attributes,
      RoadName: '济南S103',
      S103详细信息: JSON.stringify(s103Details),
    }
  } else {
    dialogTitle.value = '要素属性'
  }

  // 解析 OtherJson 数据
  try {
    if (feature.attributes.OtherJson) {
      parsedOtherJson.value = JSON.parse(feature.attributes.OtherJson)
    } else {
      parsedOtherJson.value = null
    }
  } catch (e) {
    console.warn('解析OtherJson失败:', e)
    parsedOtherJson.value = null
  }

  // Set attributes and show dialog
  attributes.value = feature.attributes
  dialogVisible.value = true

  // Zoom to the feature
  view.goTo({
    target: feature.geometry,
    zoom: 15,
  })
}

// Get label for attribute field
function getLabel(key: string) {
  const labelMap: { [key: string]: string } = {
    facilityname: '设施名称',
    facilitytype: '设施类型',
    FacilityIntroduction: '设施介绍',
    FacilityImage: '设施图片',
    Status: '状态信息',
    OtherJson: '详细信息',
    RoadName: '道路名称',
    RoadType: '道路类型',
    RoadLength: '道路长度',
    RoadImage: '道路图片',
    OwnerRoad: '所属道路',
    objectid: '对象ID',
    S103详细信息: 'S103道路详细信息',
  }
  return labelMap[key] || key
}

// 格式化 OtherJson 字段显示
function formatOtherJson(value: string) {
  if (!value) return '暂无详细信息'
  try {
    const data = JSON.parse(value)
    let formatted = ''
    for (const [key, val] of Object.entries(data)) {
      if (val !== null && val !== undefined && val !== '') {
        formatted += `${key}: ${val}\n`
      }
    }
    return formatted || '暂无详细信息'
  } catch {
    return value
  }
}

// 格式化 S103详细信息字段显示
function formatS103Details(value: string) {
  if (!value) return '暂无详细信息'
  try {
    const data = JSON.parse(value)
    let formatted = ''
    for (const [key, val] of Object.entries(data)) {
      if (val !== null && val !== undefined && val !== '') {
        formatted += `${key}: ${val}\n`
      }
    }
    return formatted || '暂无详细信息'
  } catch {
    return value
  }
}

// 根据设施类型获取状态标签
function getStatusLabel(facilitytype: string, key: string) {
  if (key !== 'Status') return getLabel(key)

  switch (facilitytype) {
    case '驿站':
      return '设备状态'
    case '景点':
      return '开放状态'
    case '餐饮':
      return '营业状态'
    default:
      return '状态信息'
  }
}

// 判断当前显示的是否为道路要素
function isRoadFeature() {
  return selectFeatureLayer?.id === roadLayer.id
}

// 图片预览功能
function previewImage(url: string) {
  previewImageUrl.value = url
  imagePreviewVisible.value = true
}

// 根据设施类型获取字段显示状态
function shouldShowField(facilitytype: string, fieldType: string) {
  switch (facilitytype) {
    case '驿站':
      return ['name', 'image', 'serviceTime', 'equipmentStatus'].includes(fieldType)
    case '景点':
      return ['name', 'image', 'introduction', 'parkingSpaces', 'chargingPiles'].includes(fieldType)
    case '餐饮':
      return ['name', 'businessInfo', 'contactInfo', 'rating'].includes(fieldType)
    default:
      return false
  }
}

// 格式化评分显示
function getRatingStars(rating: string | number) {
  const num = typeof rating === 'string' ? parseInt(rating) : rating
  if (isNaN(num) || num < 1 || num > 5) return '无评分'
  return '⭐'.repeat(num)
}
</script>

<style scoped>
.map-browsing-container {
  height: 100%;
  width: 100%;
  position: relative;
}

.map-container {
  height: 100%;
  width: 100%;
  position: relative;
}

/* Control panel styles */
.control-panel {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  background: rgba(24, 44, 78, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.15);
  transition: all 0.3s ease;
  color: #fff;
  width: 280px;
}

.panel-title {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 18px;
  color: #fff;
}

.panel-description {
  margin-bottom: 15px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

.layer-select {
  width: 100%;
  margin-top: 10px;
}

/* Dialog styles */
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.3);
  border: none;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #1976d2, #42a5f5);
  color: white;
  padding: 15px;
  border-bottom: none;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  font-weight: 600;
  color: white;
}

.attribute-form {
  padding: 10px;
}

.image-container {
  width: 100%;
  max-width: 300px;
  height: 200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  overflow: hidden;
}

.attribute-image {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  border-radius: 6px;
  cursor: pointer;
  object-fit: contain;
}

.no-image {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
  border-radius: 8px;
}

.introduction-text {
  max-height: 150px;
  overflow-y: auto;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 8px;
  color: #333;
  line-height: 1.5;
}

.s103-details {
  background: linear-gradient(135deg, #e3f2fd, #f3e5f5);
  border: 1px solid #1976d2;
  max-height: 200px;
  font-family: 'Microsoft YaHei', sans-serif;
  white-space: pre-line;
}

.feature-selector {
  max-height: 300px;
  overflow-y: auto;
}

.feature-table {
  border-radius: 8px;
  overflow: hidden;
}

.select-btn {
  padding: 4px 12px;
}

.image-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  max-height: 70vh;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  border-radius: 8px;
}
</style>
